package com.rising.face.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/1/23 17:14
 */
public class NIOClint {
    public static void main(String[] args) throws Exception {
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();

        //设置非阻塞模式
        socketChannel.configureBlocking(false);
        //提供服务器的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间，客户端不会阻塞，可以做些其他工作。。。");
                Thread.sleep(1000);
            }
        }

        //。。。如果连接成功，就发送数据
        String str = "hello，尚硅谷~~~";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());

        //发送数据，将buffer数据写入channel
        socketChannel.write(buffer);
        while (true) {
            //发送数据，将buffer数据写入channel
            socketChannel.write(buffer);
            Thread.sleep(1000);
        }
    }
}
